using System;
using System.Linq;
using Microsoft.EntityFrameworkCore;
using MvcSort.Db;
using MvcSort.Models;

namespace MvcSort.Rpostting
{
    public class EFpostting<T> : IRpostting<T> where T : BaseEntity
    {   
        private readonly DemoSort _db;
        private readonly DbSet<T> _table;
        public IQueryable<T> Tabel
        {
            get
            {
                return _table.AsQueryable<T>();
            }
        }
        
        public EFpostting()
        {
            _db= new DemoSort();
            _table=_db.Set<T>();
        }
        public void Delete(int id)
        {
            var entity = _table.FirstOrDefault(x=>x.Id==id);
            entity.IsDeleted=true;
            entity.IsActived=false;
            entity.UpdatedTime=DateTime.Now;
            _table.Update(entity);
            _db.SaveChanges();
        }

        public void Insert(T entity)
        {   
            entity.CreatedTime=DateTime.Now;
            entity.UpdatedTime=DateTime.Now;
            entity.IsDeleted=false;
            entity.IsActived=true;
            entity.DisplayOrder=entity.DisplayOrder!=0?entity.DisplayOrder:0;
            _table.Add(entity);
            _db.SaveChanges();
        }

        public void Update(T entity)
        {
            entity.UpdatedTime=DateTime.Now;
            _table.Update(entity);
            _db.SaveChanges();
        }
    }
}